#region using

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using BlogEngine.Core.Web.Controls;
using BlogEngine.Core;

#endregion

/// <summary>
/// Displays a list of posts for a specified category where [postsincategory:slug] is found in the body.
/// </summary>
[Extension("Displays a list of posts for a specified category where [postsincategory:<slug>] is found in the body", "1.0", "BlogEngine.NET")]
public class PostsInCategory :RegexMatchBase
{
    private static readonly Regex _BodyRegex = new Regex(@"\[postsincategory:(\w*)\]", RegexOptions.Compiled | RegexOptions.IgnoreCase);

    /// <summary>
    /// Hooks up an event handler to the Page and Post Serving event.
    /// </summary>
    public PostsInCategory() :base()
    {
        base.Regex = _BodyRegex;
    }

    protected override string MatchCore(Match match)
    {
        string result = string.Empty;
        Category cat = Category.GetBySlug(match.Groups[1].Value);

        if (cat != null)
        {
            List<Post> myPosts = Post.GetByCategory(cat);

            if (myPosts.Count > 0)
            {
                HtmlGenericControl ul = new HtmlGenericControl("ul");

                foreach (Post post in myPosts)
                {
                    HtmlGenericControl li = new HtmlGenericControl("li");
                    HtmlAnchor anchor = new HtmlAnchor();
                    LiteralControl date = new LiteralControl();

                    anchor.HRef = post.AbsoluteLink.ToString();
                    anchor.InnerHtml = post.Title;
                    anchor.Title = post.Description;

                    date.Text = post.DateCreated.ToString();

                    li.Controls.Add(anchor);
                    li.Controls.Add(date);
                    ul.Controls.Add(li);
                }    

                using (System.IO.StringWriter sw = new System.IO.StringWriter())
                {
                    ul.RenderControl(new HtmlTextWriter(sw));
                    result = sw.ToString();
                }
            }
        }

        return result;
    }
}
